package com.learn.sc.springbootdemo.tools;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

@Component
@EnableCaching
public class SequenceManager {
    @Autowired
    RedisService redisService;

    public static final String USER_ID = "USER_ID";

    /**
     * 递增生成sequence
     * @param sequenceName
     * @return
     */
    public String getSequence(String sequenceName){
        return String.valueOf(redisService.incr(sequenceName,1));
    }

    /**
     * 递增生成sequence拼接日期
     * @param sequenceName
     * @return
     */
    public String getSequenceByDate(String sequenceName){
        long seqId = redisService.incr(sequenceName,1);
        //补零到6位
        String seq = String.format("%06d",seqId);
        String sequence = seq.substring(seq.length()-6);
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String localDate = LocalDate.now().format(dateTimeFormatter);

        return localDate+sequence;
    }

    /**
     * 递减回退sequence
     * @param sequenceName
     * @return
     */
    public String decrSequence(String sequenceName){
        return String.valueOf(redisService.decr(sequenceName,1));
    }

    /**
     * 清零sequence
     * @param sequenceName
     * @return
     */
    public void reSetSequence(String sequenceName){
        redisService.del(sequenceName);
    }
}
